package optimizers.commons.evaluator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

public class ClusterNode {
	private String[] defaultParams;
	private boolean calculating;

	public ClusterNode(String[] defaultParams) {
		this.defaultParams = defaultParams;
	}

	public double compute(String[] params) {
		calculating = true;
		double result = -1;
		try {
			ArrayList<String> list = new ArrayList<String>(
					Arrays.asList(defaultParams));
			for (int i = 0; i < params.length; i++) {
				list.add(params[i]);
			}
			ProcessBuilder pb = new ProcessBuilder(list);
			pb.redirectError();
			Process p = pb.start();

			InputStream is = p.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);

			String line;
			while ((line = br.readLine()) != null) {
				try {
					result = Double.valueOf(line);
				} catch (Exception e) {

				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = -1;
		}
		calculating = false;
		return result;
	}

	public void setBusy() {
		this.calculating = true;
	}

	public boolean isBusy() {
		return calculating;
	}

}
